﻿#include "CComFunc.h"

#include <QCoreApplication>
#include <QDir>
#include <QThread>
#include <QTimer>
#include <QTranslator>
#include <QSettings>
#include <QSharedMemory>
#include <QDebug>
#include <string.h>

void CComFunc::qtGuiWait(unsigned long ms, bool isResponseUser)
{
    QCoreApplication::processEvents(isResponseUser ? QEventLoop::AllEvents : QEventLoop::ExcludeUserInputEvents);
    QThread::msleep(ms);
}

void CComFunc::delay(int msec)
{
    QEventLoop eventloop;
    QTimer::singleShot(msec, &eventloop, SLOT(quit()));
    eventloop.exec();
}

int CComFunc::split(char * src, const char * separator, char ** dest, int destLen)
{
    if ((src == 0) || (strlen(src) <= 0) || (separator == 0) || (strlen(separator) <= 0) || (dest == 0) || (destLen <= 0)) { return -1; }

    int size;
    size_t i, length = strlen(separator);
    dest[0] = src;

    for (size = 1; *src; ++src)
    {
        for (i = 0; i < length; ++i)
        {
            if (*src == separator[i])
            {
                *src = 0;

                if (size >= destLen) { return size; }

                dest[size++] = src + 1;
                break;
            }
        }
    }

    if (size < destLen)
    {
        dest[size] = 0;  //此处直接赋值有bug，需加上 if(size < destLen) 判断才能赋值
    }

    return size;
}

bool CComFunc::clearDir(const QString & path)
{
    if (path.isEmpty()) { return false; }

    QDir dir(path);
    if (!dir.exists()) { return true; }
    dir.setFilter(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot);  //设置过滤
    const QFileInfoList & fileList = dir.entryInfoList();                                  // 获取所有的文件信息
    foreach (QFileInfo file, fileList)
    {  //遍历文件信息
        if (file.isDir())
        {  // 递归删除
            if (!deleteDir(file.absoluteFilePath())) { qWarning() << "deleteDir error!!" << file.absoluteFilePath(); }
        }
        else
        {  // 是文件，删除
            if (!file.dir().remove(file.fileName())) { qWarning() << "removeFile error!!" << file.fileName(); }
        }
    }

    return true;  // 删除文件夹
}

bool CComFunc::deleteDir(const QString & path)
{
    if (!clearDir(path)) { qWarning() << "clearDir error!!" << path; }
    QDir dir;
    return dir.rmdir(path);  // 删除文件夹
}

bool CComFunc::checkCreateDir(const QString & path)
{
    QDir dir;
    if (!dir.exists(path)) { return dir.mkpath(path); }

    return true;
}

bool CComFunc::createEmptyDir(const QString & path)
{
    if (!clearDir(path)) { return false; }
    return checkCreateDir(path);
}

double CComFunc::average(const double * p, int len)
{
    int count2 = 0;
    double sum = 0.0;
    for (int i = 0; i < len; ++i)
    {
        if (p[i] != 0)
        {
            sum += p[i];
            ++count2;
        }
    }

    return (0 == count2) ? 0 : sum / count2;
}

double CComFunc::precision(double d, int n, bool isRounding)
{
    const double times = pow(10, n);
    const double round = isRounding ? 0.5 : 0;
    return floor(d * times + round) / times;
}

bool CComFunc::loadTranslateFile(const QString & fileName)
{
    QTranslator trans;
    return trans.load(fileName) && QCoreApplication::installTranslator(&trans);
}

static constexpr const char * AUTO_RUN = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
void CComFunc::setProcessAutoRun(const QString & appPath, bool enable)
{
    QSettings settings(AUTO_RUN, QSettings::NativeFormat);

    //以程序名称作为注册表中的键,根据键获取对应的值（程序路径）
    const QFileInfo fileInfo(appPath);
    const QString & name = fileInfo.baseName();  //键-名称

    //如果注册表中的路径和当前程序路径不一样，则表示没有设置自启动或本自启动程序已经更换了路径
    const QString & oldPath = settings.value(name).toString();    //获取目前的值-绝对路劲
    const QString & newPath = QDir::toNativeSeparators(appPath);  // toNativeSeparators函数将"/"替换为"\"
    if (enable)
    {
        if (oldPath != newPath) { settings.setValue(name, newPath); }
    }
    else
    {
        settings.remove(name);
    }
}

void CComFunc::setProcessAutoRun(bool enable) { setProcessAutoRun(QCoreApplication::applicationFilePath(), enable); }

bool CComFunc::checkAppIsRunning()
{
    static QSharedMemory shareMem(QCoreApplication::applicationName());  //创建共享内存块
    return !shareMem.create(1);
}
